using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.Extensions.Configuration;

namespace UwinEducation.MySqlBackup
{
    public class BackupSettingsForm : Form
    {
        private CheckedListBox timeListBox;
        private Button buttonAdd;
        private Button buttonRemove;
        private Button buttonSave;
        private Button buttonCancel;
        private DateTimePicker timePicker;
        private CheckBox checkBoxInterval;
        private CheckBox checkBoxScheduled;
        private NumericUpDown numericInterval;
        private Label labelMinutes;
        
        private readonly IConfiguration _configuration;
        
        public List<TimeSpan> ScheduledTimes { get; private set; }

        public BackupSettingsForm(IConfiguration configuration, List<TimeSpan> currentScheduledTimes)
        {
            _configuration = configuration;
            ScheduledTimes = new List<TimeSpan>(currentScheduledTimes);
            
            InitializeComponents();
            LoadSettings();
        }

        private void InitializeComponents()
        {
            this.Text = "备份设置";
            this.Size = new Size(400, 500);
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.StartPosition = FormStartPosition.CenterParent;
            
            // 间隔备份设置
            this.checkBoxInterval = new CheckBox();
            this.checkBoxInterval.Text = "启用间隔备份";
            this.checkBoxInterval.Location = new Point(20, 20);
            this.checkBoxInterval.Size = new Size(150, 30);
            this.checkBoxInterval.CheckedChanged += (s, e) => {
                numericInterval.Enabled = checkBoxInterval.Checked;
                labelMinutes.Enabled = checkBoxInterval.Checked;
            };
            
            this.numericInterval = new NumericUpDown();
            this.numericInterval.Location = new Point(180, 20);
            this.numericInterval.Size = new Size(80, 20);
            this.numericInterval.Minimum = 1;
            this.numericInterval.Maximum = 1440; // 最多24小时
            this.numericInterval.Value = 60; // 默认60分钟
            
            this.labelMinutes = new Label();
            this.labelMinutes.Text = "分钟";
            this.labelMinutes.Location = new Point(270, 20);
            this.labelMinutes.Size = new Size(50, 20);
            
            // 计划备份设置
            this.checkBoxScheduled = new CheckBox();
            this.checkBoxScheduled.Text = "启用计划备份";
            this.checkBoxScheduled.Location = new Point(20, 55);
            this.checkBoxScheduled.Size = new Size(150, 30);
            this.checkBoxScheduled.CheckedChanged += (s, e) => {
                timeListBox.Enabled = checkBoxScheduled.Checked;
                timePicker.Enabled = checkBoxScheduled.Checked;
                buttonAdd.Enabled = checkBoxScheduled.Checked;
                buttonRemove.Enabled = checkBoxScheduled.Checked;
            };
            
            // 时间选择器
            this.timePicker = new DateTimePicker();
            this.timePicker.Format = DateTimePickerFormat.Time;
            this.timePicker.ShowUpDown = true;
            this.timePicker.Location = new Point(20, 90);
            this.timePicker.Size = new Size(120, 20);
            
            // 添加按钮
            this.buttonAdd = new Button();
            this.buttonAdd.Text = "添加";
            this.buttonAdd.Location = new Point(150, 90);
            this.buttonAdd.Size = new Size(80, 30);
            this.buttonAdd.Click += ButtonAdd_Click;
            
            // 移除按钮
            this.buttonRemove = new Button();
            this.buttonRemove.Text = "移除";
            this.buttonRemove.Location = new Point(240, 90);
            this.buttonRemove.Size = new Size(80, 30);
            this.buttonRemove.Click += ButtonRemove_Click;
            
            // 时间列表
            this.timeListBox = new CheckedListBox();
            this.timeListBox.Location = new Point(20, 130);
            this.timeListBox.Size = new Size(340, 250);
            this.timeListBox.CheckOnClick = true;
            
            // 保存按钮
            this.buttonSave = new Button();
            this.buttonSave.Text = "保存";
            this.buttonSave.Location = new Point(180, 400);
            this.buttonSave.Size = new Size(80, 30);
            this.buttonSave.Click += ButtonSave_Click;
            
            // 取消按钮
            this.buttonCancel = new Button();
            this.buttonCancel.Text = "取消";
            this.buttonCancel.Location = new Point(280, 400);
            this.buttonCancel.Size = new Size(80, 30);
            this.buttonCancel.Click += (s, e) => this.DialogResult = DialogResult.Cancel;
            
            // 添加控件到窗体
            this.Controls.Add(this.checkBoxInterval);
            this.Controls.Add(this.numericInterval);
            this.Controls.Add(this.labelMinutes);
            this.Controls.Add(this.checkBoxScheduled);
            this.Controls.Add(this.timePicker);
            this.Controls.Add(this.buttonAdd);
            this.Controls.Add(this.buttonRemove);
            this.Controls.Add(this.timeListBox);
            this.Controls.Add(this.buttonSave);
            this.Controls.Add(this.buttonCancel);
        }

        private void LoadSettings()
        {
            // 加载间隔备份设置
            bool enableIntervalBackup = _configuration.GetValue<bool>("BackupSettings:EnableIntervalBackup", true);
            double intervalMinutes = _configuration.GetValue<double>("BackupSettings:BackupIntervalMinutes", 60);
            
            checkBoxInterval.Checked = enableIntervalBackup;
            numericInterval.Value = (decimal)intervalMinutes;
            numericInterval.Enabled = enableIntervalBackup;
            labelMinutes.Enabled = enableIntervalBackup;
            
            // 加载计划备份设置
            bool enableScheduledBackup = _configuration.GetValue<bool>("BackupSettings:EnableScheduledBackup", false);
            
            checkBoxScheduled.Checked = enableScheduledBackup;
            timeListBox.Enabled = enableScheduledBackup;
            timePicker.Enabled = enableScheduledBackup;
            buttonAdd.Enabled = enableScheduledBackup;
            buttonRemove.Enabled = enableScheduledBackup;
            
            // 加载计划时间
            RefreshTimeList();
        }

        private void RefreshTimeList()
        {
            timeListBox.Items.Clear();
            
            // 按时间排序
            ScheduledTimes.Sort((a, b) => a.CompareTo(b));
            
            foreach (var time in ScheduledTimes)
            {
                timeListBox.Items.Add(time.ToString(@"hh\:mm"), true);
            }
        }

        private void ButtonAdd_Click(object sender, EventArgs e)
        {
            TimeSpan newTime = timePicker.Value.TimeOfDay;
            
            // 检查是否已存在
            if (!ScheduledTimes.Contains(newTime))
            {
                ScheduledTimes.Add(newTime);
                RefreshTimeList();
            }
        }

        private void ButtonRemove_Click(object sender, EventArgs e)
        {
            for (int i = timeListBox.Items.Count - 1; i >= 0; i--)
            {
                if (timeListBox.GetItemChecked(i))
                {
                    string timeStr = timeListBox.Items[i].ToString();
                    if (TimeSpan.TryParse(timeStr, out TimeSpan time))
                    {
                        ScheduledTimes.Remove(time);
                    }
                }
            }
            
            RefreshTimeList();
        }

        private void ButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                // 更新配置对象
                string configPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json");
                string json = System.IO.File.ReadAllText(configPath);
                
                dynamic config = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
                
                if (config.BackupSettings == null)
                {
                    config.BackupSettings = new Newtonsoft.Json.Linq.JObject();
                }
                
                // 更新间隔备份设置
                config.BackupSettings["EnableIntervalBackup"] = checkBoxInterval.Checked;
                config.BackupSettings["BackupIntervalMinutes"] = (double)numericInterval.Value;
                
                // 更新计划备份设置
                config.BackupSettings["EnableScheduledBackup"] = checkBoxScheduled.Checked;
                
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存设置时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
} 